package cn.xiaozhu.Controller;
import cn.xiaozhu.service.facade.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author shkstart
 * @date 2019/8/28 - 14:55
 */
@Controller
public class FileController {
    @Autowired
    private IFileService fileService;
    private final static Logger logger = LoggerFactory.getLogger(FileController.class);



    /**
     * 上传文件
     * @param document
     * @param Id
     * @return
     */
    @RequestMapping(path = "/uploadFile", method = RequestMethod.POST)
    public String upload(@RequestParam(value = "document") MultipartFile document,
                         @RequestParam(value = "Id") Integer Id) {
        fileService.upload(document, Id);
        return "login";
    }



    /**
     * 下载文件
     * @param fileName
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(path = "/downloadFile", method = RequestMethod.GET)
    public void download(@RequestParam(value = "originalName") String fileName,
                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        fileService.download(fileName, request, response);
    }



    /**
     * 根据用户Id查询文件
     * @param Id
     * @param model
     * @return
     */
    @RequestMapping(path = "/selectFile")
    public String queryFile(@RequestParam(value = "Id") Integer Id, ModelMap model) {
        model.addAttribute("fileList", fileService.findAllFiles(Id));
        return "fileList";
    }




    /**
     * 删除用户文件列表里的当前文件
     * @param fileId
     * @return
     */
    @RequestMapping(path = "delFileByFileId", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> delFileByFileId(Integer fileId) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isEmpty(fileId)) {
            logger.info("false");
        }else
            try {
            fileService.delFileByFileId(fileId);
            result.put("flag", "删除成功");
            }catch (Exception e){
             logger.info("删除文件失败");
            }
            return result;
    }

}
